<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/17
 * Time: 13:01
 */

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\facade\Db;
use think\facade\View;
use think\facade\Filesystem;

class Agency extends AdminBase
{
    public function index()
    {
        return View::fetch('index');
    }

    //分类管理
    public function agency_json()
    {
        $list = \app\common\model\Agency::alias('a')->order('create_time')->paginate(10)->each(function($item, $key){
            $item->left_deposit = $item['deposit'] - $item['use_deposit'];
            $str = [];
            if(strpos($item['type'],'0') >= 0 ){
                array_push($str,'摩托车');
            }
            if(strpos($item['type'],'1') >= 0 ){
                array_push($str,'电动车');
            }

            $item['insurenum'] = Db::name('insurance')->where('aid',$item['id'])->count();
            $item['type'] = implode(',',$str);
            return $item;
        });

        $this->result($list);
    }

    //分类添加
    public function agency_add()
    {
        if ($this->request->isPost()) {
            $param = input('post.');

            $validate = new \app\admin\validate\Agency();
            $result = $validate->check($param);

            if(!$result){
                $this->error($validate->getError());
            }

            if(strtotime($param['effect_time']) >= strtotime($param['lose_time'])){
                $this->error('失效时间不能早于或等于生效时间');
            }


            if($param['isedit'] == 0){
                $param['create_time'] = time();
            }
            $param['update_time'] =time();
            $param['uid'] = session('admin_auth.admin_id');
            if($param['isedit'] == 1){
                $book = \app\common\model\Agency::find($param['id']);
            }else{
                $book = new \app\common\model\Agency();
            }

            $msg = $book->allowfield([])->save($param);
            if($msg){
                $this->success('编辑成功');
            }else{
                $this->error('编辑失败');
            }
        }

        $isedit = input('isedit');
        $map =['isedit'=> $isedit];

        if($isedit == 1){
            $data = Db::name('agency')->where('id',input('id'))->find();
            $map['data'] = $data;
        }

        return $this->fetch('agency_edit',$map);
    }

    //分类删除
    public function agency_del()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $uid = Db::name('agency')->where('id','in',$param['id'])->value('uid');
            if(session('admin_auth.admin_id') != 1 || $uid != session('admin_auth.admin_id')) $this->error('无权进行此操作');

            Db::name('agency')->where('id','in',$param['id'])->delete();
            insert_admin_log('删除了机构');
            $this->success('删除成功');
        }
    }
}